package com.laker.admin.module.ext.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laker.admin.framework.aop.metrics.Metrics;
import com.laker.admin.framework.aop.ratelimit.RateLimit;
import com.laker.admin.framework.aop.trace.TraceCodeBlock;
import com.laker.admin.framework.model.PageResponse;
import com.laker.admin.framework.model.Response;
import com.laker.admin.module.ext.controller.params.XmglZlsjApiSyncParam;
import com.laker.admin.module.ext.controller.params.XmglZlsjPageParam;
import com.laker.admin.module.ext.controller.params.XmglZlsjSUParam;
import com.laker.admin.module.ext.entity.XmglZlsjDO;
import com.laker.admin.module.ext.service.IXmglZlsjService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目管理-智链商机
 *
 * @author zhangqingshan
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/ext/xmgl_zlsj")
@Metrics
public class XmglZlsjController {
    @Autowired
    private IXmglZlsjService xmglZlsjService;

    private final String CHECK_API_KEY = "fasdhgfdarweqrvxsas";

    /**
     * API 同步
     * 通过参数中的key进行限制
     *
     * @param param 参数
     * @return {@link Response }
     */
    @PostMapping("/apiSync")
    @Transactional(rollbackFor = Exception.class)
    @RateLimit(key = "zlsj.apiSync")
    public Response apiSync(@RequestBody XmglZlsjApiSyncParam param) {
        if (StringUtils.equals(param.getKey(), CHECK_API_KEY)) {
            return Response.error500("key异常");
        }
        List<XmglZlsjDO> collect = param.getValues().stream().map(p -> {
            XmglZlsjDO xmglZlsjDO = new XmglZlsjDO();
            xmglZlsjDO.setBiaoti(p.getBiaoti());
            xmglZlsjDO.setLianjie(p.getLianjie());
            xmglZlsjDO.setRiqi(p.getRiqi());
            xmglZlsjDO.setLaiyuan(p.getLaiyuan());
            return xmglZlsjDO;
        }).collect(Collectors.toList());
        xmglZlsjService.saveBatch(collect);
        return Response.ok();
    }


    /**
     * 手动新增/改
     * 权限：zlsj.edit
     *
     * @param param 参数
     * @return {@link Response }
     */
    @PostMapping
    @SaCheckPermission("zlsj.edit")
    @Transactional(rollbackFor = Exception.class)
    public Response saveOrUpdate(@RequestBody @Validated XmglZlsjSUParam param) {
        if (StringUtils.isBlank(param.getBiaoti()) && param.getId() == null) {
            return Response.error("新增商机，标题不能为空");
        }
        XmglZlsjDO xmglZlsjDO = new XmglZlsjDO();
        xmglZlsjDO.setId(param.getId());
        xmglZlsjDO.setBiaoti(param.getBiaoti());
        xmglZlsjDO.setLianjie(param.getLianjie());
        xmglZlsjDO.setRiqi(param.getRiqi());
        xmglZlsjDO.setLaiyuan(param.getLaiyuan());
        xmglZlsjService.saveOrUpdate(xmglZlsjDO);
        return Response.ok();
    }


    /**
     * 删除智链商机
     * 逻辑删除，权限：zlsj.del
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("zlsj.del")
    @Transactional(rollbackFor = Exception.class)
    public Response delete(@PathVariable Long id) {
        xmglZlsjService.update(Wrappers.lambdaUpdate(XmglZlsjDO.class)
                .eq(XmglZlsjDO::getId, id)
                .eq(XmglZlsjDO::getIsDel, true));
        return Response.ok();
    }


    /**
     * 审阅
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @GetMapping("/review/{id}")
    @SaCheckPermission("zlsj.edit")
    @Transactional(rollbackFor = Exception.class)
    public Response review(@PathVariable Long id) {
        xmglZlsjService.update(Wrappers.lambdaUpdate(XmglZlsjDO.class)
                .eq(XmglZlsjDO::getId, id)
                .eq(XmglZlsjDO::getShifouyiyue, true)
                .eq(XmglZlsjDO::getShenyueren, StpUtil.getLoginId())
                .eq(XmglZlsjDO::getShenyunshijian, DateUtil.date()));
        return Response.ok();
    }

    /**
     * 分页查询
     * 权限：zlsj.list
     *
     * @param param 参数
     * @return {@link PageResponse }
     */
    @SaCheckPermission("zlsj.list")
    @PostMapping("/page")
    public PageResponse page(@RequestBody XmglZlsjPageParam param) {
        Page page = param.toPage();

        IPage<XmglZlsjDO> pageList = TraceCodeBlock.trace("xmglZlsjService.page",
                () -> xmglZlsjService.page(page, Wrappers.lambdaQuery(XmglZlsjDO.class)
                        .eq(XmglZlsjDO::getIsDel, false)
                        .ge(param.getRiqiStart() != null, XmglZlsjDO::getRiqi, param.getRiqiStart())
                        .le(param.getRiqiEnd() != null, XmglZlsjDO::getRiqi, DateUtil.endOfDay(param.getRiqiEnd()))
                        .eq(param.getShifouyiyue() != null && param.getShifouyiyue(), XmglZlsjDO::getShifouyiyue, param.getShifouyiyue())
                        .ne(param.getShifouyiyue() != null && !param.getShifouyiyue(), XmglZlsjDO::getShifouyiyue, true)
                        .like(StringUtils.isNotBlank(param.getBiaoti()), XmglZlsjDO::getBiaoti, param.getBiaoti())
                        .like(StringUtils.isNotBlank(param.getLaiyuan()), XmglZlsjDO::getLaiyuan, param.getLaiyuan())
                        .eq(param.getShenyueren() != null, XmglZlsjDO::getShenyueren, param.getShenyueren())
                        .ge(param.getShenyunshijianStart() != null, XmglZlsjDO::getShenyunshijian, param.getShenyunshijianStart())
                        .le(param.getShenyunshijianEnd() != null, XmglZlsjDO::getShenyunshijian, param.getShenyunshijianEnd())
                        .orderByDesc(StringUtils.isBlank(param.getOrderBy()), XmglZlsjDO::getCreateTime)));

        return PageResponse.ok(pageList.getRecords(), pageList.getTotal());
    }

    /**
     * 获取详情
     * 权限：zlsj.list
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @GetMapping("/{id}")
    @SaCheckPermission("zlsj.list")
    public Response get(@PathVariable("id") Long id) {
        return Response.ok(xmglZlsjService.getById(id));
    }
}
